import axios from '@/utils/axios'
import { baseUrl as API_HOST } from '/env'

const DOCUMENT_UPLOAD = '' // 默认上传地址

export default {
  async upload(params, url = DOCUMENT_UPLOAD) {
    const formData = new FormData()
    Object.keys(params).forEach(key => {
      formData.append(key, params[key])
    })

    try {
      const res = await axios.post(API_HOST + url, formData)
      if (res.data.code === 0) {
        return res.data.data
      } else {
        throw new Error(res.data.msg)
      }
    } catch (e) {
      throw new Error(e)
    }
  },

  /**
   * 批量上传
   * @param params  参数
   * @param files 文件列表
   * @param url 上传地址
   * @param fileParamsName 文件参数名
   * @returns {Promise<*>}
   */
  async uploadBatch(params, files, url = DOCUMENT_UPLOAD, fileParamsName = 'files') {
    const formData = new FormData()
    Object.keys(params).forEach(key => {
      formData.append(key, params[key])
    })

    if(files && files.length > 0) {
      files.forEach(file => {
        formData.append(fileParamsName, file)
      })
    }

    try {
      const res = await axios.post(API_HOST + url, formData)
      if (res.data.code === 0) {
        return res.data.data
      } else {
        throw new Error(res.data.msg)
      }
    } catch (e) {
      throw new Error(e)
    }
  }
}
